package com.jackrain.nea.omslocal.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import com.aliyun.openservices.ons.api.impl.util.MsgConvertUtil;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;

/**
 * @Discription: 发送消息中间表的失败消息
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2018/1/4 10:24
 */
@Component
@Slf4j
public class SendFailedMsgService {

    @Autowired
    private SendMqServies sendMqServies;
    @Autowired
    private ProducerBean producerBean;
    @Autowired
    private PropertiesConf pconf;


    /**
     * 自动查询消息中间表待发消息
     */
    public void queryFailedmsg() {

        String querySql = "select * from t_failedmsg where sendstatus = 0 and rownum <= 50 order by creationdate for update skip locked";
        JSONArray msgArr = QueryEngine.getInstance().doQueryObjectArray(querySql);
        if (msgArr == null){
           //  没有待发消息
            return;
        }
        for (Object obj:msgArr
             ) {
            JSONObject tempObj = JSONObject.parseObject(obj.toString());

            if (tempObj.getJSONObject("msgbody") ==  null){
                // 消息体为空, 不需重发
                continue;
            }
            this.sendFailedMsg(tempObj.getString("topic"),tempObj.getString("tag"),tempObj.getJSONObject("msgbody"));
        }

        // 修改已发送消息的状态

    }

    public void sendFailedMsg(String topic,String tag,JSONObject msgbody) {

        Message msg = null;
        String str = UUID.randomUUID().toString();
        try {
            msg = new Message(topic, tag, MsgConvertUtil
                    .objectSerialize(msgbody));
            msg.setKey(str);
            SendResult sendResult = producerBean.send(msg);
            assert sendResult != null;
            log.debug("send success: MSGKEY[" + str + "] ---" + topic + "========" + tag);

        } catch (ONSClientException e) {
           // 网络问题,消息发送失败


        }catch (IOException i){
            // 序列化,流错误
            log.debug("序列化错误,消息发送失败");

        }


    }


}
